﻿using Microsoft.Win32;
using System.Collections.Generic;
using System.Management.Automation;

namespace DeployTools
{
  [Cmdlet(VerbsCommon.Get, "InstalledBTDFApplications")]
  public class GetInstalledBTDFApplications : PSCmdlet
  {
    protected override void ProcessRecord()
    {
      RegistryKey products;
      RegistryKey product;
      RegistryKey installProperties;
      RegistryKey components;
      RegistryKey component;
      BtdfApplicationInstallInfo info;
      Dictionary<string, string> comps;

      comps = new Dictionary<string, string>();

      using (components = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Components"))
      {
        foreach (string key2 in components.GetSubKeyNames())
        {
          using (component = components.OpenSubKey(key2))
          {
            if (component != null)
            {
              foreach (string s in component.GetValueNames())
              {
                string v = component.GetValue(s) as string;
                if (v != null)
                {
                  if (v.EndsWith(".btdfproj"))
                  {
                    if (!comps.ContainsKey(s))
                    {
                      comps.Add(s, v);
                    }
                  }
                }
              }
            }
          }
        }
      }

      using (products = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Products"))
      {
        foreach (string key in products.GetSubKeyNames())
        {
          using (product = products.OpenSubKey(key))
          {
            if (product != null)
            {
              using (installProperties = product.OpenSubKey("InstallProperties"))
              {
                if (installProperties != null)
                {
                  info = new BtdfApplicationInstallInfo();

                  info.DisplayName = installProperties.GetValue("DisplayName") as string;
                  info.UninstallString = installProperties.GetValue("UninstallString") as string;
                  

                  if (comps.ContainsKey(key))
                  {
                    info.BtdfProjPath = comps[key];
                    info.UninstallString = info.UninstallString.Substring(info.UninstallString.IndexOf(' ') + 1);
                    WriteObject(info);
                  }
                }
              }
            }
          }
        }
      }
    }
  }

  public class BtdfApplicationInstallInfo
  {
    public string DisplayName { get; set; }
    public string UninstallString { get; set; }
    public string BtdfProjPath { get; set; }
  }
}
